package com.yfree.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.yfree.R;
import com.yfree.YConfig;
import com.yfree.application.YApplication;
import com.yfree.interfaces.YBroadcastReceiver;
import com.yfree.interfaces.YBroadcastReceiver2;
import com.yfree.libs.actionsheet.baoyz.ActionSheet;
import com.yfree.libs.permission.YPermission;
import com.yfree.listeners.YAjaxCallBack;
import com.yfree.listeners.YPermissionListener;
import com.yfree.models.YBroadcastModel;
import com.yfree.utils.YAppUtils;
import com.yfree.utils.YCrashHandler;
import com.yfree.utils.YSDCardUtils;
import com.yfree.utils.YToastUtils;
import com.yfree.utils.net.YJsonKV;
import com.yfree.utils.net.YNetUtil;
import com.yfree.utils.net.YResponseUtils;
import com.yfree.views.YProgressDialog;
import com.yfree.views.YSildingFinishLayout;
import com.yfree.views.YSildingFinishLayout.OnSildingFinishListener;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.core.Arrays;
import net.tsz.afinal.http.AjaxParams;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class YActivity extends FragmentActivity {
    public YActivity() {
    }

    public YActivity(Activity context) {
        this.context = context;
    }

    public List<YBroadcastModel> broadcastReceivers = new ArrayList<>();
    private List<BroadcastReceiver> broadcastReceivers2 = new ArrayList<>();
    private List<String> broadcastReceiverFilters2 = new ArrayList<>();

    private InputMethodManager inputMethodManager;
    private AlertDialog alertDialog;
    private ActionSheet actionSheet;
    private boolean upDownAnim = false;
    private boolean systemBarTintEnable = true;
    private boolean userStatuBarPadding = true;
    private boolean fitsSystemWindows = true;
    private boolean closeInputOutside = true;
    private boolean checkSDCard = YConfig.checkSDCard;
    private YSildingFinishLayout slidinglView;
    private boolean slidingFinishLayoutBindViewPager;
    public View contentView = null;

    public Activity context = this; // 框架内使用，为兼容Flutter
    public YActivity yContext = this; // 框架内不要使用！！！
    public YApplication yApplication;
    public SparseArray<YPermissionListener> yPermissionCallBacks;
    public SharedPreferences ySharedPreferences;
    public FragmentManager yFragmentManager;
    public String yBasePath;
    public NotificationManager yNotificationManager;
    public boolean yDoInput = true;
    public Bundle yBundle;
    public DisplayMetrics yDisplayMetrics;
    //public Handler yHandler = new YHandler(context);

    /*private static class YHandler extends Handler {
        private final WeakReference<YActivity> mActivity;

        YHandler(YActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActivity.get() != null) {
                super.handleMessage(msg);
            }
        }
    }*/

    /**
     * 在onCreate之前调用
     */
    public void ySetCloseInputOutside(boolean closeInputOutside) {
        this.closeInputOutside = closeInputOutside;
    }

    /**
     * 在onCreate之前调用
     */
    public void ySetCheckSDCard(boolean checkSDCard) {
        this.checkSDCard = checkSDCard;
    }

    /**
     * 在onCreate之前调用
     */
    public void yUseUpDownAnim(boolean upDownAnim) {
        this.upDownAnim = upDownAnim;
    }

    /**
     * 在onCreate之前调用
     */
    public void ySetStatuBarEnable(boolean systemBarTintEnable) {
        systemBarTintEnable_hadChange = true;
        this.systemBarTintEnable = systemBarTintEnable;
    }

    /**
     * 在onCreate之前调用
     */
    public void ySetUseStatuBarPadding(boolean userStatuBarPadding) {
        userStatuBarPadding_hadChange = true;
        this.userStatuBarPadding = userStatuBarPadding;
    }

    /**
     * 在onCreate之前调用
     */
    public void ySetFitsSystemWindows(boolean fitsSystemWindows) {
        fitsSystemWindows_hadChange = true;
        this.fitsSystemWindows = fitsSystemWindows;
    }

    private boolean systemBarTintEnable_hadChange = false;
    private boolean userStatuBarPadding_hadChange = false;
    private boolean fitsSystemWindows_hadChange = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
        if (targetSdkVersion > Build.VERSION_CODES.O)
            context.getApplicationInfo().targetSdkVersion = Build.VERSION_CODES.O;
        if (!systemBarTintEnable_hadChange)
            ySetStatuBarEnable(true);
        if (!userStatuBarPadding_hadChange)
            ySetUseStatuBarPadding(false);
        if (!fitsSystemWindows_hadChange)
            ySetFitsSystemWindows(true);
        yDoInput = false;
        super.onCreate(savedInstanceState);
        context = this;
        getApplicationInfo().targetSdkVersion = targetSdkVersion;
        if (YConfig.yCrashHandlerAble)
            if (context instanceof YActivity)
                YCrashHandler.init((YActivity) context);
        if (context instanceof YActivity)
            YActivityManager.getActivities().add((YActivity) context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (YConfig.stopScreenShotAble)
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        if (yDoInput)
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            if (YConfig.isStatuBarTinkDark && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
        }
        yDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(yDisplayMetrics);
        overridePendingTransition(upDownAnim ? R.anim.base_slide_bottom_in : R.anim.base_slide_right_in, upDownAnim ? R.anim.base_slide_bottom_out : R.anim.base_slide_right_out);
        if (yNotificationManager == null)
            yNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (yApplication == null)
            try {
                yApplication = (YApplication) getApplication();
            } catch (Exception ignored) {
            }
        if (yFragmentManager == null)
            yFragmentManager = getSupportFragmentManager();
        if (ySharedPreferences == null)
            ySharedPreferences = getSharedPreferences(YConfig.YSHAREDPREFERENCESNAME, Context.MODE_PRIVATE);
        try {
            yBundle = getIntent().getExtras();
        } catch (Exception ignored) {
        }
    }

    public boolean isAlive() {
        try {
            return !isFinishing() && !isDestroyed();
        } catch (Exception ignored) {
            try {
                return !isFinishing();
            } catch (Exception ignored2) {
                return false;
            }
        }
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    public void yRunOnUIThread(Runnable action) {
        if (isAlive())
            runOnUiThread(action);
    }

    public Timer yRunOnUIThread(long delay, final Runnable action) {
        if (isAlive()) {
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    yRunOnUIThread(action);
                    timer.cancel();
                }
            }, delay);
            return timer;
        }
        return null;
    }

    public Timer yRunOnUIThread(long delay, long loop, final Runnable action) {
        if (isAlive()) {
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    yRunOnUIThread(action);
                }
            }, delay, loop);
            return timer;
        }
        return null;
    }

    public void yRunOnTimer(Runnable action) {
        yRunOnTimer(0, action);
    }

    public Timer yRunOnTimer(long delay, final Runnable action) {
        if (isAlive()) {
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    action.run();
                    timer.cancel();
                }
            }, delay);
            return timer;
        }
        return null;
    }

    public Timer yRunOnTimer(long delay, long loop, final Runnable action) {
        if (isAlive()) {
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    action.run();
                }
            }, delay, loop);
            return timer;
        }
        return null;
    }

    /**
     * 在setContentView之后调用
     */
    public void ySetAsStatuBarLayoutParams(View view) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                if (view.getParent() instanceof LinearLayout)
                    view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, yGetStatuBarHeight()));
                else if (view.getParent() instanceof RelativeLayout)
                    view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, yGetStatuBarHeight()));
                else
                    view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, yGetStatuBarHeight()));
            else
                view.setVisibility(View.GONE);
        } catch (Exception ignored) {
        }
    }

    public void yBindViewPagerForSlidingFinishLayout(ViewPager viewPager) {
        if (slidinglView != null && !slidingFinishLayoutBindViewPager) {
            slidingFinishLayoutBindViewPager = true;
            slidinglView.setViewPagerPosition(viewPager.getCurrentItem());
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i1) {
                }

                @Override
                public void onPageSelected(int i) {
                    slidinglView.setViewPagerPosition(i);
                }

                @Override
                public void onPageScrollStateChanged(int i) {
                }
            });
        }
    }

    public void yCheckSDCard() {
        if (context instanceof YActivity) {
//            yDoPermissionThing(new YPermissionListener((YActivity) context) {
//                @Override
//                public void onSuccessed() {
//                    if (!YSDCardUtils.existSDCard()) {
//                        yShowBuilder("存储空间不可用，为确保正常运行，请检查存储空间！", new OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                YActivityManager.finishApplication();
//                            }
//                        }, null, false);
//                        return;
//                    }
//                    if (YSDCardUtils.getSDFreeSize() < YConfig.MINSDCARDSPACE) {
//                        yShowBuilder("存储空间不足，为确保正常运行，请及时清理存储空间！", new OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                YActivityManager.finishApplication();
//                            }
//                        }, null, false);
//                        return;
//                    }
//                    yBasePath = Environment.getExternalStorageDirectory().getAbsolutePath() + YConfig.PROJECTBASEDIR;
//                    File file = new File(yBasePath);
//                    if (!file.exists())
//                        if (!file.mkdirs()) {
//                            yShowBuilder("初始化app目录失败，请检查存储空间！", new OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    YActivityManager.finishApplication();
//                                }
//                            }, null, false);
//                            return;
//                        }
//                    onYStorageReady();
//                }
//            }, Permission.STORAGE);
            if (!YSDCardUtils.existSDCard()) {
                yShowBuilder("存储空间不可用，为确保正常运行，请检查存储空间！", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        YActivityManager.finishApplication();
                    }
                }, null, false);
                return;
            }
            if (YSDCardUtils.getSDFreeSize() < YConfig.MINSDCARDSPACE) {
                yShowBuilder("存储空间不足，为确保正常运行，请及时清理存储空间！", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        YActivityManager.finishApplication();
                    }
                }, null, false);
                return;
            }
            yBasePath = getExternalFilesDir(YConfig.YFreeDir).getAbsolutePath() + YConfig.PROJECTBASEDIR;
            File file = new File(yBasePath);
            if (!file.exists())
                if (!file.mkdirs()) {
                    yShowBuilder("初始化app目录失败，请检查存储空间！", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            YActivityManager.finishApplication();
                        }
                    }, null, false);
                    return;
                }
            onYStorageReady();
        }
    }

    protected void onYStorageReady() {
    }

    @Override
    public void setContentView(int layoutResID) {
        setContentView(layoutResID, false);
    }

    public void setContentView(int layoutResID, boolean scrollAble) {
        setContentView(yInflate(layoutResID), scrollAble);
    }

    public void setContentView(View view, boolean scrollAble) {
        view.setFitsSystemWindows(fitsSystemWindows);
        view.setBackgroundColor(Color.BLACK);
        if (scrollAble) {
            slidinglView = (YSildingFinishLayout) yInflate(R.layout.activity_scroll_finish);
            view.setLayoutParams(new YSildingFinishLayout.LayoutParams(YSildingFinishLayout.LayoutParams.MATCH_PARENT, YSildingFinishLayout.LayoutParams.MATCH_PARENT));
            slidinglView.addView(view);
            slidinglView.setOnSildingFinishListener(new OnSildingFinishListener() {
                @Override
                public void onSildingFinish() {
                    finish();
                }
            });
            setContentView(slidinglView);
        } else
            setContentView(view);
    }

    @Override
    public void setContentView(final View view) {
        contentView = getShadowContentView(view);
        super.setContentView(contentView);
        FinalActivity.initInjectedView(context);
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                yOnCreated();
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    private View getShadowContentView(View contentView) {
        int shadowWidth = yGetDimen(R.dimen.shadow_width);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int statuBarHeight = yGetStatuBarHeight();
            LinearLayout h_linearLayout = new LinearLayout(context);
            h_linearLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            h_linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            h_linearLayout.setPadding(-shadowWidth, -yGetStatuBarHeight(), 0, 0);
            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(shadowWidth, LinearLayout.LayoutParams.MATCH_PARENT));
            imageView.setImageResource(R.drawable.shadow);
            h_linearLayout.addView(imageView);
            h_linearLayout.addView(contentView);
            LinearLayout v_linearLayout = new LinearLayout(context);
            v_linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            v_linearLayout.setOrientation(LinearLayout.VERTICAL);
            if (systemBarTintEnable) {
                ImageView imageView_statuBar = new ImageView(context);
                imageView_statuBar.setScaleType(ImageView.ScaleType.FIT_XY);
                ySetAsStatuBarLayoutParams(imageView_statuBar);
                imageView_statuBar.setImageResource(YConfig.statubar);
                v_linearLayout.addView(imageView_statuBar);
            } else {
                if (userStatuBarPadding)
                    contentView.setPadding(0, statuBarHeight, 0, 0);
            }
            contentView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, systemBarTintEnable ? yDisplayMetrics.heightPixels : LinearLayout.LayoutParams.MATCH_PARENT));
            v_linearLayout.addView(h_linearLayout);
            return v_linearLayout;
        } else {
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setPadding(-shadowWidth, 0, 0, 0);
            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(shadowWidth, LinearLayout.LayoutParams.MATCH_PARENT));
            imageView.setImageResource(R.drawable.shadow);
            linearLayout.addView(imageView);
            contentView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            linearLayout.addView(contentView);
            return linearLayout;
        }
    }

    private void yOnCreated() {
        if (checkSDCard)
            yCheckSDCard();
        onYCreated();
    }

    public void onYCreated() {
    }

    public int yGetStatuBarHeight() {
        return getResources().getDimensionPixelSize(getResources().getIdentifier("status_bar_height", "dimen", "android"));
    }

    public int yGetNavBarHeight() {
        return getResources().getDimensionPixelSize(getResources().getIdentifier("navigation_bar_height", "dimen", "android"));
    }

    public static boolean yCheckDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0)
            hasNavigationBar = rs.getBoolean(id);
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception ignored) {
        }
        return hasNavigationBar;
    }

    public void yDoPermissionThing(final YPermissionListener permissionCallBack, final String... permissions) {
        if (YPermission.hasPermission(context, permissions))
            // 有权限，直接do anything.
            permissionCallBack.onSucceed(0, Arrays.asList(permissions));
        else
            // 没有权限,申请权限。
            if (TextUtils.isEmpty(YConfig.requestPermissonMessage))
                doPermissionThing(permissionCallBack, permissions);
            else
                yShowBuilder(YConfig.requestPermissonMessage, "我知道了", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doPermissionThing(permissionCallBack, permissions);
                    }
                }, null, false);
    }

    private void doPermissionThing(YPermissionListener permissionCallBack, String... permissions) {
        if (yPermissionCallBacks == null)
            yPermissionCallBacks = new SparseArray<>();
        int requestCode = YPermissionListener.defaultRequestCode + 1;
        while (true) {
            if (yPermissionCallBacks.get(requestCode) == null) {
                yPermissionCallBacks.put(requestCode, permissionCallBack);
                YPermission.with(context).requestCode(requestCode).callback(permissionCallBack).permission(permissions).start();
                break;
            }
            requestCode++;
            if (requestCode > Short.MAX_VALUE)
                requestCode = YPermissionListener.defaultRequestCode + 1;
        }
    }

    public String yGetString(int stringId) {
        return context.getResources().getString(stringId);
    }

    public int yGetDimen(int dimenId) {
        return (int) context.getResources().getDimension(dimenId);
    }

    public int yGetColor(int colorId) {
        return context.getResources().getColor(colorId);
    }

    public float yGetDpByPx(int dp) {
        return Resources.getSystem().getDisplayMetrics().density * dp;
    }

    public void yLog(String msg) {
        yLog(YConfig.YLOGTAG, msg);
    }

    public void yLog(String tag, String msg) {
        if (YConfig.DEBUG)
            Log.e(tag, "YFreeLog：" + msg);
    }

    public void yPost(final String jkid, final YJsonKV kv, final YAjaxCallBack<?> callBack) {
        yPost(jkid, kv, callBack, true);
    }

    public void yPost(final String jkid, final YJsonKV kv, final YAjaxCallBack<?> callBack, final boolean showProgress) {
        yPost(YConfig.IP, jkid, kv, callBack, showProgress);
    }

    public void yPost(final String ip, final String jkid, final YJsonKV kv, final YAjaxCallBack<?> callBack, final boolean showProgress) {
        if (TextUtils.isEmpty(ip)) {
            String msg = "yPost工具ip缺失，请配置YConfig或传入ip";
            yLog(msg);
            if (callBack.getShowProgress()) yToast(msg);
            callBack.onFail(null, null, "", msg);
            return;
        }
        if (!YNetUtil.isNetAble(context)) {
            yShowReloadBuilder(jkid, kv, callBack, showProgress);
            return;
        }
        YJsonKV tempKV = kv != null ? kv : new YJsonKV();
        callBack.setJkid(jkid);
        callBack.setJsonKv(tempKV);
        callBack.setShowProgress(showProgress);
        final AjaxParams params = new AjaxParams();
        params.put("jkid", jkid);
        if (!TextUtils.isEmpty(YConfig.JKXLH))
            params.put("jkxlh", YConfig.JKXLH);
        params.put("jkparam", YResponseUtils.compress(tempKV));
        YApplication.getFinalHttp().post(ip, params, callBack);
    }

    public Object yPostSync(final String jkid, final YJsonKV kv) {
        yLog(jkid + ":SyncRequest", kv.toString());
        AjaxParams params = new AjaxParams();
        params.put("jkid", jkid);
        if (!TextUtils.isEmpty(YConfig.JKXLH))
            params.put("jkxlh", YConfig.JKXLH);
        params.put("jkparam", YResponseUtils.compress(kv));
        Object response = YApplication.getFinalHttp().postSync(YConfig.IP, params);
        try {
            yLog(jkid + ":SyncResultSuccess", YConfig.compressParamsAble ? YResponseUtils.deCompress(response.toString()) : response.toString());
        } catch (Exception e) {
            if (YConfig.DEBUG)
                yToast("同步请求的响应数据不合法：\n" + (response != null ? YConfig.compressParamsAble ? YResponseUtils.deCompress(response.toString()) : response.toString() : "（空）"));
        }
        return response;
    }

    private void yShowReloadBuilder(final String jkid, final YJsonKV json, final YAjaxCallBack callBack, final Boolean showProgress) {
        yShowBuilder("网络不可用，请检查网络！！！", "重试", YActivityManager.getActivities().size() > 1 ? "返回" : "设置", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                yPost(jkid, json, callBack, showProgress != null ? showProgress : true);
            }
        }, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (YActivityManager.getActivities().size() > 1)
                    finish();
                else {
                    yShowReloadBuilder(jkid, json, callBack, showProgress);
                    try {
                        startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
//                        startActivity(new Intent().setComponent(new ComponentName("com.android.settings", "com.android.settings.WirelessSettings")).setAction("android.yIntent.action.VIEW"));
                    } catch (Exception ignored) {
                        yToast("请手动开启网络");
                    }
                }
            }
        }, false);
    }

    public void yToast(final CharSequence message) {
        if (YConfig.canShowToast)
            yRunOnUIThread(new Runnable() {
                @Override
                public void run() {
                    YToastUtils.toast(context, message);
                }
            });
    }

    public void yShowBuilder(final String message, final OnClickListener onPositiveListener, final OnClickListener onNegativeListener, final boolean cancelable) {
        yShowBuilder(message, "确定", onPositiveListener, onNegativeListener, cancelable);
    }

    public void yShowBuilder(final String message, final String posTitle, final OnClickListener onPositiveListener, final OnClickListener onNegativeListener, final boolean cancelable) {
        yShowBuilder(message, posTitle, "取消", onPositiveListener, onNegativeListener, cancelable);
    }

    public void yShowBuilder(final String message, final String posTitle, final String negTitle, final OnClickListener onPositiveListener, final OnClickListener onNegativeListener, final boolean cancelable) {
        yRunOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (alertDialog != null)
                    alertDialog.dismiss();
                if (isAlive()) {
                    Builder builder = new Builder(context).setCustomTitle(getBuilderView(YAppUtils.getAppName(context) + "提示", true)).setMessage(message).setCancelable(cancelable);
                    if (onPositiveListener != null)
                        builder.setPositiveButton(posTitle, onPositiveListener);
                    if (onNegativeListener != null || cancelable)
                        builder.setNegativeButton(negTitle, onNegativeListener);
                    try {
                        alertDialog = builder.create();
                        alertDialog.setCancelable(cancelable);
                        alertDialog.setCanceledOnTouchOutside(cancelable);
                        alertDialog.show();
                    } catch (Exception ignored) {
                    }
                }
            }
        });
    }

    private View getBuilderView(String title, boolean showIcon) {
        View builderView = yInflate(R.layout.builder_title);
        ((ImageView) builderView.findViewById(R.id.imageView_icon)).setImageResource(YConfig.logo_icon);
        if (!showIcon)
            builderView.findViewById(R.id.imageView_icon).setVisibility(View.GONE);
        ((TextView) builderView.findViewById(R.id.textView_title)).setText(title);
        return builderView;
    }

    public void yShowSelectBuilder(final String[] items, final OnClickListener listener) {
        yShowSelectBuilder(null, items, listener);
    }

    public void yShowSelectBuilder(final String title, final String[] items, final OnClickListener listener) {
        yRunOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (isAlive()) {
                    Builder builder = new Builder(context).setItems(items, listener);
                    if (!TextUtils.isEmpty(title))
                        builder.setCustomTitle(getBuilderView(title, false));
                    try {
                        builder.create().show();
                    } catch (Exception ignored) {
                    }
                }
            }
        });
    }

    public void yShowActionSheet(String title, String[] items, ActionSheet.ItemClickListener itemClickListener, String cancelItem, ActionSheet.CancelListener cancelListener) {
        if (actionSheet != null)
            try {
                actionSheet.dismiss();
            } catch (Exception ignored) {
            }
        if (isAlive())
            try {
                actionSheet = ActionSheet.init(context).setTitle(title).setTheme(R.style.ActionSheetByTheme).setItemTexts(items).setItemClickListener(itemClickListener).setCancelText(cancelItem, cancelListener).show();
            } catch (Exception ignored) {
            }
    }

    public View yInflate(int layoutId) {
        return context.getLayoutInflater().inflate(layoutId, null);
    }

    public void yIntent(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        if (bundle != null)
            intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public void yIntentForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent(context, cls);
        if (bundle != null)
            intent.putExtras(bundle);
        context.startActivityForResult(intent, requestCode);
    }

    public void yCloseInputMethod() {
        if (inputMethodManager == null)
            inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive())
            inputMethodManager.hideSoftInputFromWindow(context.getWindow().getDecorView().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void yRegisterReceiver(String action, final YBroadcastReceiver receiver) {
        boolean hasRegisterd = false;
        for (YBroadcastModel yBroadcastModel : broadcastReceivers)
            if (yBroadcastModel.action.equals(action)) {
                hasRegisterd = true;
                break;
            }
        if (!hasRegisterd) broadcastReceivers.add(new YBroadcastModel(action, receiver));
        else
            yLog("You should not use yRegisterReceiver with the same action in one YActivity,The action should be single in one YActivity!");
    }

    public void yUnregisterReceiver(String action) {
        for (int i = broadcastReceivers.size() - 1; i >= 0; i--)
            if (broadcastReceivers.get(i).action.equals(action))
                broadcastReceivers.remove(i);
    }

    public void ySendBroadcast(String action) {
        ySendBroadcast(action, null);
    }

    public void ySendBroadcast(String action, final Bundle bundle) {
        for (YActivity yActivity : YActivityManager.getActivities()) {
            for (final YBroadcastModel yBroadcastModel : yActivity.broadcastReceivers) {
                if (yBroadcastModel.action.equals(action)) {
                    yRunOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            yBroadcastModel.receiver.onReceive(bundle);
                        }
                    });
                }
            }
        }
    }

    public void unregisterReceivers() {
        for (int i = broadcastReceivers.size() - 1; i >= 0; i--)
            yUnregisterReceiver(broadcastReceivers.get(i).action);
        broadcastReceivers.clear();
    }

    //=============================== ySendBroadcast2 ==================================
    public Intent yRegisterReceiver2(String filter, final YBroadcastReceiver2 receiver) {
        if (broadcastReceiverFilters2.contains(filter)) return null;
        else {
            broadcastReceiverFilters2.add(filter);
            return registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    receiver.onReceive(context, intent);
                }
            }, new IntentFilter(filter));
        }
    }

    @Override
    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
        broadcastReceivers2.add(receiver);
        return (context instanceof YActivity) ? super.registerReceiver(receiver, filter) : context.registerReceiver(receiver, filter);
    }

    @Override
    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) {
        broadcastReceivers2.add(receiver);
        return (context instanceof YActivity) ? super.registerReceiver(receiver, filter, broadcastPermission, scheduler) : context.registerReceiver(receiver, filter, broadcastPermission, scheduler);
    }

    @Override
    public void unregisterReceiver(BroadcastReceiver receiver) {
    }

    public void unregisterReceivers2() {
        for (BroadcastReceiver receiver : broadcastReceivers2)
            try {
                if (context instanceof YActivity)
                    super.unregisterReceiver(receiver);
                else
                    context.unregisterReceiver(receiver);
            } catch (Exception ignored) {
            }
        broadcastReceivers2.clear();
        broadcastReceiverFilters2.clear();
    }

    public void ySendBroadcast2(String action) {
        try {
            context.sendBroadcast(new Intent(action));
        } catch (Exception ignored) {
        }
    }

    public void ySendBroadcast2(String action, Bundle bundle) {
        try {
            context.sendBroadcast(new Intent(action).putExtras(bundle));
        } catch (Exception ignored) {
        }
    }
    //=============================== ySendBroadcast2 ==================================

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void finish() {
        super.finish();
        if (upDownAnim)
            overridePendingTransition(R.anim.base_slide_bottom_in, R.anim.base_slide_bottom_out);
        else
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_right_out);
    }

    public void finish(View v) {
        finish();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (closeInputOutside)
            yCloseInputMethod();
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (YProgressDialog.isShowing) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        yCloseInputMethod();
        unregisterReceivers();
        unregisterReceivers2();
        if (context instanceof YActivity)
            YProgressDialog.dismissProgress((YActivity) context);
        try {
            alertDialog.dismiss();
        } catch (Exception ignored) {
        }
        try {
            actionSheet.windowManager.removeViewImmediate(actionSheet);
        } catch (Exception ignored) {
        }
        YActivityManager.getActivities().remove(this);
        if (yApplication != null)
            yApplication.cleanMemory();
        //yApplication = null;
        //context = null;
        //yHandler = null;
        super.onDestroy();
    }

    @Override
    public void onTrimMemory(int level) {
        if (yApplication != null)
            yApplication.cleanMemory();
        super.onTrimMemory(level);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (true) return;
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    }
}
